<template>

  <a-card :bordered="false">
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false" >
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-form-item  label="芯片编号" >
          <a-input v-model:value="model.ringcode" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onfinish">查询</a-button>
        </a-form-item>
      </a-form-model>
    </j-form-container>
    <j-form-container :disabled="true">
      <a-form-model ref="formold" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24" class="user_top">
            {{model.mname}}
          </a-col>
        </a-row>
        <a-row style="height: 80px;background-color: red;">
          <a-col :span="24"  class="user_info" >
            {{model.pcode}}
          </a-col>
          <a-col :span="24"  class="user_text">
            {{model.player}} - {{model.groupid}}  {{model.score}}
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" class="user_buttom">
            {{model.morg}}
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>

    <a-row style="padding: 10px 10px">
      <a-col :md="8" :sm="24" >
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="startCall" :disabled="canjl">开始检录</a-button>
              <a-button style="margin-left: 8px" @click="stopCall" :disabled="!canjl">停止检录</a-button>
              <a-button style="margin-left: 16px" @click="toCall" >已检录名单</a-button>
            </span>
      </a-col>
    </a-row>
  </a-card>

</template>

<script>

import { validateDuplicateValue } from '@/utils/util'
import store from '@/store/'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getAction,postAction } from '@api/manage'

export default {
  name: 'PlayerShow',
  components: {
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data () {
    return {
      model:{
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      websock: null,
      canjl:false,
      lockReconnect: false,
      //websocket错误连接次数
      wsConnectErrorTime:1,
      heartCheck:null,
      validatorRules: {
        player: [
          { required: true, message: '请输入人员!'},
          { validator: (rule, value, callback) => validateDuplicateValue('runner_match_player_show', 'player', value, this.model.id, callback)},
        ],
        ringcode: [
          { required: true, message: '请输入芯片编号!'},
          { validator: (rule, value, callback) => validateDuplicateValue('runner_match_player_show', 'ringcode', value, this.model.id, callback)},
        ],
      }
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
  },
 created () {
    //备份model原始值
    //this.canjl=false
   debugger
  },
  mounted() {
    this.websocketOnclose();
    getAction("/match/canCall",{}).then(res=>{
      console.log(res);
      if(res.success){
        this.canjl=res.result;
        if(this.canjl){
          this.initWebSocket();
        }

      }
    })
  },
  beforedestory: function () { // 离开页面生命周期函数
    this.websocketOnclose();
  },
  methods: {
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id;
      var url = window._CONFIG['domianURL'].replace("https://","wss://").replace("http://","ws://")+"/mqtt/"+userId;
      //console.log(url);
      //update-begin-author:taoyan date:2022-4-22 for:  v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
      let token = Vue.ls.get(ACCESS_TOKEN)
      this.websock = new WebSocket(url, [token]);
      //update-end-author:taoyan date:2022-4-22 for:  v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen: function () {
      console.log("Mqtt连接成功");
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnerror: function (e) {
      console.log("WebSocket连接发生错误，第%s次",this.wsConnectErrorTime);

      this.wsConnectErrorTime = this.wsConnectErrorTime + 1;
      if(this.wsConnectErrorTime>5){
        console.log("WebSocket连接错误超过5次，就不再重新连了！");
        this.lockReconnect = true
        return;
      }

      this.reconnect();
    },
    websocketOnmessage: function (e) {
      var data = eval("(" + e.data + ")"); //解析对象
      console.log("-----接收消息-------",data);
      if(data.success){
        this.model=data.result;
      }
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnclose: function (e) {
      if(this.websock!=null){
        this.websock.close();
        console.log("connection closed (" + e + ")");
        if(e){
          console.log("connection closed (" + e.code + ")");
        }
        //this.reconnect();
      }
    },
    websocketSend(text) { // 数据发送
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
    },
    reconnect() {
      var that = this;
      if(that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 20000);
    },
    heartCheckFun(){
      var that = this;
      //心跳检测,每20s心跳一次
      that.heartCheck = {
        timeout: 20000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function(){
          clearTimeout(this.timeoutObj);
          //clearTimeout(this.serverTimeoutObj);
          return this;
        },
        start: function(){
          var self = this;
          this.timeoutObj = setTimeout(function(){
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            that.websocketSend("HeartBeat");
            console.info("客户端发送心跳");
            //self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
            //  that.websock.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            //}, self.timeout)
          }, this.timeout)
        }
      }
    },
    onfinish(){
      console.log(this.model.ringcode);
      getAction("/match/callInfo/"+this.model.ringcode,{}).then(res=>{
        console.log(res);
        if(res.success){
          this.model=res.result;
        }else{
            this.$message.error(res.message);
        }
      })
    },
    toCall(){
      var url="http://"+window.location.host+"/online/cgreport/1612723682975744001?matchid1="+this.model.matchid+"&matchid2="+this.model.matchid;
      window.open(url);
    },
    showDetail(key,data){
      this.$notification.close(key);
      var id = data.msgId;
      getAction(this.url.queryById,{id:id}).then((res) => {
        if (res.success) {
          var record = res.result;
          this.showAnnouncement(record);
        }
      })

    },
    startCall(){
     // this.initWebSocket();
      postAction("/match/startCall",{}).then(res=>{
        console.log(res);
        this.canjl=true;
        this.initWebSocket();
      })
    },
    stopCall(){
      // this.initWebSocket();
      postAction("/match/stopCall",{}).then(res=>{
        console.log(res);
        this.websocketOnclose();
        this.canjl=false;
      })
    }

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.user_top{
  background-color: #d9edf7;
  height: 60px;
  font-size: large;
  font-weight: bolder;
  text-align: center;
  padding: 20px 0;
}
.user_info{
  background-color: red;
  height: 140px;
  color: azure;
  font-size: xxx-large;
  font-weight: bolder;
  text-align: center;
  padding: 40px 0;
}
.user_buttom{
  background-color: #d9edf7;
  height: 60px;
  font-size: large;
  font-weight: bolder;
  text-align: center;
  padding: 20px 0;
}
.user_text{
  background-color: red;
  height: 40px;
  font-size: large;
  font-weight: bolder;
  text-align: center;
  padding: 5px 0;
}
</style>